<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'

const props = defineProps({
  content: {
    type: String,
    default: ''
  },
  fileInfo: {
    type: Object,
    default: null
  },
  placement: {
    type: String,
    default: 'top'
  },
  delay: {
    type: Number,
    default: 500
  }
})

const tooltipRef = ref(null)
const triggerRef = ref(null)
const visible = ref(false)
const position = ref({ x: 0, y: 0 })
let showTimer = null
let hideTimer = null

const tooltipContent = computed(() => {
  if (props.fileInfo) {
    return {
      name: props.fileInfo.name,
      path: props.fileInfo.path,
      size: props.fileInfo.size,
      modTime: props.fileInfo.modTime,
      isDir: props.fileInfo.isDir
    }
  }
  return { text: props.content }
})

const formatFileSize = (bytes) => {
  if (!bytes || bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const updatePosition = (event) => {
  // 使用鼠标位置而不是元素位置
  const mouseX = event.clientX
  const mouseY = event.clientY
  
  // 设置初始位置在鼠标右下方
  let x = mouseX + 10
  let y = mouseY + 10
  
  // 如果tooltip已经渲染，进行边界检测
  const tooltipRect = tooltipRef.value?.getBoundingClientRect()
  if (tooltipRect) {
    // 右边界检测
    if (x + tooltipRect.width > window.innerWidth - 8) {
      x = mouseX - tooltipRect.width - 10
    }
    // 下边界检测
    if (y + tooltipRect.height > window.innerHeight - 8) {
      y = mouseY - tooltipRect.height - 10
    }
    // 左边界检测
    if (x < 8) x = 8
    // 上边界检测
    if (y < 8) y = 8
  }
  
  position.value = { x, y }
}

const showTooltip = (event) => {
  clearTimeout(hideTimer)
  // 立即设置位置，避免首次显示在左上角
  updatePosition(event)
  showTimer = setTimeout(() => {
    visible.value = true
    // 显示后再次更新位置以确保准确性
    setTimeout(() => updatePosition(event), 0)
  }, props.delay)
}

const hideTooltip = () => {
  clearTimeout(showTimer)
  hideTimer = setTimeout(() => {
    visible.value = false
  }, 100)
}

const handleMouseEnter = (event) => {
  showTooltip(event)
}

const handleMouseLeave = () => {
  hideTooltip()
}

const handleMouseMove = (event) => {
  if (visible.value) {
    updatePosition(event)
  }
}

onMounted(() => {
  if (triggerRef.value) {
    triggerRef.value.addEventListener('mouseenter', handleMouseEnter)
    triggerRef.value.addEventListener('mouseleave', handleMouseLeave)
    triggerRef.value.addEventListener('mousemove', handleMouseMove)
  }
})

onUnmounted(() => {
  clearTimeout(showTimer)
  clearTimeout(hideTimer)
  if (triggerRef.value) {
    triggerRef.value.removeEventListener('mouseenter', handleMouseEnter)
    triggerRef.value.removeEventListener('mouseleave', handleMouseLeave)
    triggerRef.value.removeEventListener('mousemove', handleMouseMove)
  }
})
</script>

<template>
  <div ref="triggerRef" class="tooltip-trigger">
    <slot></slot>
  </div>
  
  <Teleport to="body">
    <div 
      v-if="visible"
      ref="tooltipRef"
      class="tooltip"
      :style="{
        left: position.x + 'px',
        top: position.y + 'px'
      }"
    >
      <div v-if="tooltipContent.name" class="tooltip-file-info">
        <div class="tooltip-title">{{ tooltipContent.name }}</div>
        <div class="tooltip-details">
          <div class="tooltip-item">
            <span class="tooltip-label">路径:</span>
            <span class="tooltip-value">{{ tooltipContent.path }}</span>
          </div>
          <div v-if="!tooltipContent.isDir" class="tooltip-item">
            <span class="tooltip-label">大小:</span>
            <span class="tooltip-value">{{ formatFileSize(tooltipContent.size) }}</span>
          </div>
          <div class="tooltip-item">
            <span class="tooltip-label">修改时间:</span>
            <span class="tooltip-value">{{ formatDate(tooltipContent.modTime) }}</span>
          </div>
        </div>
      </div>
      <div v-else class="tooltip-text">
        {{ tooltipContent.text }}
      </div>
    </div>
  </Teleport>
</template>

<style scoped>
.tooltip-trigger {
  display: inline-block;
  width: 100%;
}

.tooltip {
  position: fixed;
  z-index: 9999;
  background: var(--tooltip-bg, #2d3748);
  color: var(--tooltip-text, #ffffff);
  border-radius: 6px;
  padding: 8px 12px;
  font-size: 12px;
  line-height: 1.4;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  max-width: 300px;
  word-wrap: break-word;
  pointer-events: none;
}

.tooltip-file-info {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.tooltip-title {
  font-weight: 600;
  font-size: 13px;
  color: var(--tooltip-title, #ffffff);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding-bottom: 4px;
}

.tooltip-details {
  display: flex;
  flex-direction: column;
  gap: 3px;
}

.tooltip-item {
  display: flex;
  gap: 6px;
}

.tooltip-label {
  color: var(--tooltip-label, #a0aec0);
  min-width: 60px;
  flex-shrink: 0;
}

.tooltip-value {
  color: var(--tooltip-text, #ffffff);
  word-break: break-all;
}

.tooltip-text {
  color: var(--tooltip-text, #ffffff);
}

/* 浅色主题 */
.light-theme .tooltip {
  --tooltip-bg: #1a202c;
  --tooltip-text: #ffffff;
  --tooltip-title: #ffffff;
  --tooltip-label: #a0aec0;
}

/* 深色主题 */
.dark-theme .tooltip {
  --tooltip-bg: #2d3748;
  --tooltip-text: #ffffff;
  --tooltip-title: #ffffff;
  --tooltip-label: #a0aec0;
}
</style>